package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.entity.Alarm;
import com.example.smartwaterapi.service.AlarmService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 闹钟控制器
 */
@Slf4j
@Tag(name = "闹钟管理", description = "闹钟相关接口")
@RestController
@RequestMapping("/api/alarm")
public class AlarmController {

    @Autowired
    private AlarmService alarmService;

    @Operation(summary = "同步闹钟", description = "同步用户设置的闹钟到服务器")
    @PostMapping("/sync")
    public RestApiResponse<String> syncAlarm(@RequestBody Alarm alarm) {
        try {
            log.info("同步闹钟: userId={}, name={}, time={}:{}", 
                alarm.getUserId(), alarm.getName(), alarm.getHour(), alarm.getMinute());
            
            boolean success = alarmService.syncAlarm(alarm);
            if (success) {
                return RestApiResponse.ok("闹钟同步成功");
            } else {
                return RestApiResponse.businessError("50001", "闹钟同步失败");
            }
        } catch (Exception e) {
            log.error("同步闹钟异常", e);
            return RestApiResponse.businessError("50001", "同步失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量同步闹钟", description = "批量同步用户设置的闹钟到服务器")
    @PostMapping("/sync/batch")
    public RestApiResponse<String> syncAlarms(@RequestBody List<Alarm> alarms) {
        try {
            log.info("批量同步闹钟: 共{}个闹钟", alarms.size());
            
            boolean success = alarmService.syncAlarms(alarms);
            if (success) {
                return RestApiResponse.ok("批量闹钟同步成功");
            } else {
                return RestApiResponse.businessError("50001", "批量闹钟同步失败");
            }
        } catch (Exception e) {
            log.error("批量同步闹钟异常", e);
            return RestApiResponse.businessError("50001", "同步失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户闹钟列表", description = "根据用户ID获取闹钟列表")
    @GetMapping("/user/{userId}")
    public RestApiResponse<List<Alarm>> getUserAlarms(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            List<Alarm> alarms = alarmService.getAlarmsByUserId(userId);
            return RestApiResponse.ok(alarms);
        } catch (Exception e) {
            log.error("获取用户闹钟列表异常: userId={}", userId, e);
            return RestApiResponse.businessError("50001", "获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户设备闹钟列表", description = "根据用户ID和设备ID获取闹钟列表")
    @GetMapping("/user/{userId}/device/{deviceId}")
    public RestApiResponse<List<Alarm>> getUserDeviceAlarms(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "设备ID") @PathVariable Long deviceId) {
        try {
            List<Alarm> alarms = alarmService.getAlarmsByUserIdAndDeviceId(userId, deviceId);
            return RestApiResponse.ok(alarms);
        } catch (Exception e) {
            log.error("获取用户设备闹钟列表异常: userId={}, deviceId={}", userId, deviceId, e);
            return RestApiResponse.businessError("50001", "获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除闹钟", description = "根据闹钟ID删除闹钟")
    @DeleteMapping("/{alarmId}")
    public RestApiResponse<String> deleteAlarm(
            @Parameter(description = "闹钟ID") @PathVariable Long alarmId) {
        try {
            boolean success = alarmService.removeById(alarmId);
            if (success) {
                return RestApiResponse.ok("闹钟删除成功");
            } else {
                return RestApiResponse.businessError("50001", "闹钟删除失败");
            }
        } catch (Exception e) {
            log.error("删除闹钟异常: alarmId={}", alarmId, e);
            return RestApiResponse.businessError("50001", "删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "启用/禁用闹钟", description = "根据闹钟ID启用或禁用闹钟")
    @PutMapping("/{alarmId}/status")
    public RestApiResponse<String> updateAlarmStatus(
            @Parameter(description = "闹钟ID") @PathVariable Long alarmId,
            @Parameter(description = "状态 0:禁用 1:启用") @RequestParam Integer status) {
        try {
            Alarm alarm = new Alarm();
            alarm.setId(alarmId);
            alarm.setStatus(status);
            alarm.setIsEnabled(status == 1);
            
            boolean success = alarmService.updateById(alarm);
            if (success) {
                return RestApiResponse.ok("闹钟状态更新成功");
            } else {
                return RestApiResponse.businessError("50001", "闹钟状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新闹钟状态异常: alarmId={}, status={}", alarmId, status, e);
            return RestApiResponse.businessError("50001", "更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取已禁用的闹钟列表", description = "获取用户所有已禁用的闹钟（包括触发完成的单次闹钟）")
    @GetMapping("/user/{userId}/disabled")
    public RestApiResponse<List<Alarm>> getDisabledAlarms(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            List<Alarm> disabledAlarms = alarmService.getDisabledAlarmsByUserId(userId);
            return RestApiResponse.ok(disabledAlarms);
        } catch (Exception e) {
            log.error("获取已禁用闹钟列表异常: userId={}", userId, e);
            return RestApiResponse.businessError("50001", "获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "手动禁用单次闹钟", description = "手动禁用已触发的单次闹钟（用于测试和管理）")
    @PutMapping("/{alarmId}/disable-once")
    public RestApiResponse<String> disableOnceAlarm(
            @Parameter(description = "闹钟ID") @PathVariable Long alarmId) {
        try {
            // 获取闹钟信息
            Alarm alarm = alarmService.getById(alarmId);
            if (alarm == null) {
                return RestApiResponse.businessError("40001", "闹钟不存在");
            }
            
            // 检查是否为单次闹钟
            if (alarm.getRepeatMode() != 0) {
                return RestApiResponse.businessError("40002", "只能禁用单次闹钟");
            }
            
            // 禁用单次闹钟
            Alarm updateAlarm = new Alarm();
            updateAlarm.setId(alarmId);
            updateAlarm.setIsEnabled(false);
            updateAlarm.setNextTriggerTime(null);
            updateAlarm.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean success = alarmService.updateById(updateAlarm);
            if (success) {
                return RestApiResponse.ok("单次闹钟禁用成功");
            } else {
                return RestApiResponse.businessError("50001", "单次闹钟禁用失败");
            }
        } catch (Exception e) {
            log.error("禁用单次闹钟异常: alarmId={}", alarmId, e);
            return RestApiResponse.businessError("50001", "禁用失败: " + e.getMessage());
        }
    }

    @Operation(summary = "测试重复模式解析", description = "测试前端重复模式位操作的解析结果（开发测试用）")
    @GetMapping("/test/repeat-mode/{repeatMode}")
    public RestApiResponse<String> testRepeatMode(
            @Parameter(description = "重复模式") @PathVariable Integer repeatMode) {
        try {
            StringBuilder result = new StringBuilder();
            result.append("重复模式 ").append(repeatMode).append(" (二进制: ")
                  .append(Integer.toBinaryString(repeatMode)).append(") 的解析结果:\n");
            
            if (repeatMode == 0) {
                result.append("- 单次闹钟（不重复）");
            } else if (repeatMode == 1) {
                result.append("- 每天重复");
            } else if (repeatMode == 62) {
                result.append("- 工作日重复（周一到周五，编码：2+4+8+16+32=62）");
            } else if (repeatMode == 192) {
                result.append("- 周末重复（周六周日，编码：64+128=192）");
            } else {
                result.append("- 自定义重复模式: ");
                String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
                boolean first = true;
                
                // 前端编码：位1-7对应周一到周日
                for (int i = 1; i <= 7; i++) {
                    if (((repeatMode >> i) & 1) == 1) {
                        if (!first) result.append(", ");
                        result.append(weekDays[i-1]); // weekDays数组从0开始，所以i-1
                        first = false;
                    }
                }
            }
            
            return RestApiResponse.ok(result.toString());
        } catch (Exception e) {
            log.error("测试重复模式异常: repeatMode={}", repeatMode, e);
            return RestApiResponse.businessError("50001", "测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 清理孤儿闹钟
     */
    @Operation(summary = "清理孤儿闹钟", description = "删除设备已不存在的闹钟")
    @PostMapping("/cleanup/orphan")
    public RestApiResponse<String> cleanupOrphanAlarms() {
        try {
            int cleanedCount = alarmService.cleanupOrphanAlarms();
            String message = cleanedCount > 0 ? 
                String.format("成功清理了%d个孤儿闹钟", cleanedCount) : 
                "没有发现孤儿闹钟";
            return RestApiResponse.ok(message);
        } catch (Exception e) {
            log.error("清理孤儿闹钟异常", e);
            return RestApiResponse.businessError("50001", "清理失败: " + e.getMessage());
        }
    }
} 